# Copyright (c) 2009 Chuck Thier
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.

class AcceptOverrideMiddleware(object):
    def __init__(self, app, global_conf=None, **kwargs):
        """
        WSGI middleware that overrides the HTTP_ACCEPT header if configured
        extensions are appended to the url path.

        For example if a request is made to /users.json it will set the
        HTTP_ACCEPT header to application/json, and remove .json from the path.

        An example config might look like:
       
            [filter:accept_override]
            use = egg:resttools#accept_override
            html = text/html
            json = application/json

            [app:my_app]
            ...
            filter-with = accept_override

        :param app: WSGI application

        :param global_conf: Dictonary of global config.  Not used.

        :param **kwargs: Dictonary of application config.
        """
        self.app = app
        self.overrides = kwargs

    def __call__(self, env, start_response):
        parts = env['PATH_INFO'].rsplit('.',1)
        if len(parts) > 1:
            ending = parts[-1]
            if ending in self.overrides:
                env['HTTP_ACCEPT'] = self.overrides[ending]
                env['PATH_INFO'] = env['PATH_INFO'][:-(len(ending)+1)]
        return self.app(env, start_response)

# The following factories are used as entrypoints for Paste
def accept_filter_factory(global_conf, **kwargs):
    def filter(app):
        return AcceptOverrideMiddleware(app, global_conf, **kwargs)
    return filter

def accept_filter_app_factory(app, global_conf, **kwargs):
    return AcceptOverrideMiddleware(app, global_conf, **kwargs)
